﻿using Sustainalytics.SharedEntities.EsgResearch;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Sustainalytics.ClientDW.Synchronization.SyncESGData.AbstractClassesAndInterfaces;

namespace Sustainalytics.ClientDW.Synchronization.SyncESGData.RPCompanyProfileLogic
{
    public class RPCompanyProfileOrchestrator : ICoreEsgSyncOrchestrator<EsgResearchProfile>, IComprehensiveEsgSyncOrchestrator<EsgResearchProfile>
    {
        private readonly RPCompanyProfileMapper rpCompanyProfileMapper;
        private readonly RPCompanyProfileCommand rpCompanyProfileCommand;

        public RPCompanyProfileOrchestrator(RPCompanyProfileMapper rpCompanyProfileMapper, RPCompanyProfileCommand rpCompanyProfileCommand)
        {
            this.rpCompanyProfileMapper = rpCompanyProfileMapper;
            this.rpCompanyProfileCommand = rpCompanyProfileCommand;
        }        

        async Task ICoreEsgSyncOrchestrator<EsgResearchProfile>.OrchestrateAsync(IList<EsgResearchProfile> coreEsgResearchProfiles, IList<Guid> invalidatedCompaniesIds)
        {
            await OrchestrateAsync(invalidatedCompaniesIds, coreEsgResearchProfiles, false);
        }

        async Task IComprehensiveEsgSyncOrchestrator<EsgResearchProfile>.OrchestrateAsync(IList<EsgResearchProfile> comprehensiveEsgResearchProfiles, IList<Guid> invalidatedCompaniesIds)
        {
            await OrchestrateAsync(invalidatedCompaniesIds, comprehensiveEsgResearchProfiles, true);
        }

        private async Task OrchestrateAsync(IList<Guid> invalidatedCompaniesIds, IList<EsgResearchProfile> esgResearchProfiles, bool isComprehensiveEsgResearch)
        {
            var rpCompanyProfiles = rpCompanyProfileMapper.MapManyToMany(esgResearchProfiles);

            rpCompanyProfiles.ToList().ForEach(rp => rp.HasFullESGResearch = isComprehensiveEsgResearch);

            await rpCompanyProfileCommand.ExecuteAsync(rpCompanyProfiles, invalidatedCompaniesIds).ConfigureAwait(false);
        }
    }
}
